#!/bin/python3
import gi
gi.require_version('Gtk', '3.0')
import  os, subprocess, locale
from mlocale import translate
from gi.repository import Gtk, GdkPixbuf


class MService(Gtk.Window):
	def __init__(self):
		Gtk.Window.__init__(self)

		self.set_title("Servis Yöneticisi")
		self.set_default_size(360,500)

		box = Gtk.VBox()
		self.add(box)

		self.services_black_list = ["halt","initbase","random","rc","reboot","sendsignals"]
		self.icon_dir = "./icons"
		if not os.path.exists(self.icon_dir):
			self.icon_dir = "/usr/share/mservice/icons"
			self.set_icon(GdkPixbuf.Pixbuf.new_from_file("/usr/share/icons/hicolor/scalable/apps/mservice.svg"))
		else:
			self.set_icon(GdkPixbuf.Pixbuf.new_from_file("{}/mservice.svg".format(self.icon_dir)))

		self.search_widget = Gtk.SearchEntry()
		self.search_widget.connect("search-changed",self.search_change)
		box.pack_start(self.search_widget,False,False,5)

		self.services_store = Gtk.ListStore(GdkPixbuf.Pixbuf(),str)
		self.services_tree = Gtk.TreeView(model=self.services_store)
		self.services_tree.set_activate_on_single_click(True)
		self.services_tree.connect("button-release-event",self.click_tree)

		tree_icon = Gtk.CellRendererPixbuf()
		tree_icon.set_fixed_size(32,32)
		icon = Gtk.TreeViewColumn(_[1],tree_icon,gicon = 0)
		self.services_tree.append_column(icon)

		tree_text = Gtk.CellRendererText()
		text = Gtk.TreeViewColumn(_[2],tree_text, text = 1)
		self.services_tree.append_column(text)

		scroll = Gtk.ScrolledWindow()
		scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
		scroll.add(self.services_tree)
		box.pack_start(scroll,True, True, 5)

		self.get_services()
		self.append_tree(self.services)

	def click_tree(self,widget,event):
		selected = self.services_tree.get_selection()
		tree_model, tree_iter = selected.get_selected()
		select = tree_model[tree_iter][1]
		status = self.services[select]
		if event.button == 1:
			if status:
				text = _[3].format(select)
			else:
				text = _[4].format(select)
			question = Gtk.MessageDialog(self,0,Gtk.MessageType.QUESTION, Gtk.ButtonsType.OK_CANCEL,_[5])
			question.set_title(_[5])
			question.format_secondary_text(text)
			get = question.run()
			if get == Gtk.ResponseType.OK:
				if status:
					get = subprocess.Popen(["/usr/aylinux/bin/service","stop",select], stdout = subprocess.PIPE)
				else:
					get = subprocess.Popen(["/usr/aylinux/bin/service","start",select], stdout = subprocess.PIPE)
				get.wait()
				return_text, err = get.communicate()
				if " FAIL " in str(return_text):
					error_msg = Gtk.MessageDialog(self,0,Gtk.MessageType.INFO, Gtk.ButtonsType.OK,_[11])
					error_msg.set_title(_[11])
					if status:
						error_text = _[13].format(select)
					else:
						error_text = _[14].format(select)
					error_msg.format_secondary_text(error_text)
					get = error_msg.run()
					error_msg.destroy()
				self.get_services()
				self.search_widget.set_text("")
				self.append_tree(self.services)
			question.destroy()
		elif event.button == 3:
			menu = Gtk.Menu()
			enable = Gtk.MenuItem(_[6])
			enable.connect("activate",self.enable_service,select)
			menu.add(enable)
			disable = Gtk.MenuItem(_[7])
			disable.connect("activate",self.disable_service,select)
			menu.add(disable)
			menu.show_all()
			menu.popup_at_pointer()
			print(select)

	def subprocess_parse(self,get):
		get = get.communicate()[0]
		get = get.decode("utf-8","strict")
		return get

	def enable_service(self,widget,service):
		get = subprocess.Popen(["/usr/aylinux/bin/service","enable",service], stdout = subprocess.PIPE)
		get.wait()
		get = self.subprocess_parse(get)
		info = Gtk.MessageDialog(self,0,Gtk.MessageType.INFO, Gtk.ButtonsType.OK,_[8].format(service))
		info.set_title(_[8].format(service))
		info.format_secondary_text(get)
		info.run()
		info.destroy()

	def disable_service(self,widget,service):
		get = subprocess.Popen(["/usr/aylinux/bin/service","disable",service], stdout = subprocess.PIPE)
		get.wait()
		get = self.subprocess_parse(get)
		info = Gtk.MessageDialog(self,0,Gtk.MessageType.INFO, Gtk.ButtonsType.OK,_[9].format(service))
		info.set_title(_[9].format(service))
		info.format_secondary_text(get)
		info.run()
		info.destroy()

	def get_services(self):
		self.services = {}
		service_dir = "/etc/init.d"
		if os.path.exists(service_dir):
			services = os.listdir(service_dir)
			for service in services:
				if service not in self.services_black_list:
					self.services[service] = self.get_service_status(service)
		else:
			dialog = Gtk.MessageDialog(None,0, Gtk.MessageType.ERROR,
			Gtk.ButtonsType.OK, "Hata")
			dialog.format_secondary_text(_[10].format(service_dir))
			dialog.run()
			self.destroy()

	def get_service_status(self,service):
		get = subprocess.Popen(["/usr/aylinux/bin/service","status",service], stdout = subprocess.PIPE)
		get.wait()
		get = self.subprocess_parse(get)
		get = get.split("\n")[0]
		get = get.split(" ")
		if "çalışıyor" in get:
			return True
		else:
			return False

	def search_change(self,search_widget):
		search_text = search_widget.get_text()
		s = {}
		for service in self.services.keys():
			if search_text in service:
				s[service] = self.services[service]
		self.append_tree(s)

	def append_tree(self,services):
		self.services_store.clear()
		keys_list = list(services.keys())
		keys_list.sort()
		for service in keys_list:
			service_state = services[service]
			if service_state:
				icon = GdkPixbuf.Pixbuf.new_from_file("{}/2.svg".format(self.icon_dir))
			else:
				icon = GdkPixbuf.Pixbuf.new_from_file("{}/1.svg".format(self.icon_dir))
			self.services_store.append([icon,service])


if __name__ == "__main__":
	l = locale.getdefaultlocale()
	l = l[0].split("_")[0]
	locales = list(translate.translate.keys())
	if l not in locales:
		l = "en"
	_ = translate.translate[l]
	if os.getuid() != 0:
		dialog = Gtk.MessageDialog(None,0, Gtk.MessageType.ERROR,
		Gtk.ButtonsType.OK, _[11])
		dialog.format_secondary_text(_[12])
		dialog.run()
	else:
		pen = MService()
		pen.connect("destroy", Gtk.main_quit)
		pen.show_all()
		Gtk.main()